/**
 * Created by Sunny on 2017-08-15.
 */
import * as types from '../mutation-types'
import { getCookie, setCookie, delCookie } from '../util'
const state = {
  username: '',
  loginType: '',
  isLogin: false
}

const getters = {
  username: state => {
    let username = getCookie('username')
    if (username == null) {
      return state.username
    } else {
      return username
    }
  },
  isLogin: state => {
    let isLogin = getCookie('isLogin')
    if (isLogin == null) {
      return state.isLogin
    } else {
      return isLogin
    }
  },
  loginType: state => {
    let loginType = getCookie('loginType')
    if (loginType == null) {
      return state.loginType
    } else {
      return loginType
    }
  }
}

const actions = {
  initUser: ({commit, state}, userInfo) => commit(types.INIT_LOGIN_USER, {userInfo}),
  destroyUser: ({commit, state}) => commit(types.DESTORY_LOGIN_USER)
}
const mutations = {
  [types.INIT_LOGIN_USER] (state, { userInfo }) {
    state.user = userInfo
    state.isLogin = true
    let expireDays = 1000 * 60 * 30
    setCookie('isLogin', state.isLogin, expireDays)
    setCookie('username', state.user.username, expireDays)
    setCookie('loginType', state.user.loginType, expireDays)
  },
  [types.DESTORY_LOGIN_USER] (state) {
    state.isLogin = false
    delCookie('isLogin')
    delCookie('username')
    delCookie('loginType')
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
